/*
 *  Copyright (C) 2011 Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * pn_AddServer.java
 *
 * Created on 04/06/2011, 17:21:08
 */
package kuasar.plugin.servermanager.gui.actions;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

import kuasar.plugin.Intercom.GUI;
import kuasar.plugin.servermanager.Config;
import kuasar.plugin.servermanager.gui.pn_Main;
import kuasar.plugin.servermanager.network.utils.IP;
import kuasar.plugin.utils.XML;

/**
 *
 * @author Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 */
public class pn_AddServer extends kuasar.plugin.classMod.AbstractPanel{

     private pn_Main panel;
     private int timeLeft =10;
     private boolean autosave= true;
     private int port;
     private Timer autoclose= new Timer (1000, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            if(timeLeft>0){
                bt_cancel.setText("Close ("+ timeLeft--+")");
                
            }else{
                bt_cancel.setText("Closing");
                autoclose.stop();
                GUI.visibleToolBar();
                GUI.loadPlugin(panel);
            }
        }
         
     });
     
     
    /** Creates new form pn_AddServer */
    public pn_AddServer(pn_Main panel) {
        this.panel = panel;
        initComponents();
        hideErrors();
        GUI.invisibleToolBar();
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pn_Container = new javax.swing.JPanel();
        lbl_title = new javax.swing.JLabel();
        lbl_hostname = new javax.swing.JLabel();
        txt_hostname = new javax.swing.JTextField();
        lbl_Address = new javax.swing.JLabel();
        txt_Address = new javax.swing.JTextField();
        lbl_BAddress = new javax.swing.JLabel();
        lbl_BName = new javax.swing.JLabel();
        pn_scan = new javax.swing.JPanel();
        lbl_Port = new javax.swing.JLabel();
        txt_Port = new javax.swing.JTextField();
        lbl_BPort = new javax.swing.JLabel();
        bt_accept = new javax.swing.JButton();
        bt_cancel = new javax.swing.JButton();

        setOpaque(false);

        pn_Container.setOpaque(false);

        lbl_title.setFont(new java.awt.Font("Dialog", 1, 18));
        lbl_title.setForeground(new java.awt.Color(204, 204, 204));
        lbl_title.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/server.png"))); // NOI18N
        lbl_title.setText("Add Server");

        lbl_hostname.setForeground(new java.awt.Color(204, 204, 204));
        lbl_hostname.setText("Hostname:");

        txt_hostname.setBackground(new Color(0,0,0,0));
        txt_hostname.setForeground(new java.awt.Color(204, 204, 204));
        txt_hostname.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txt_hostname.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        txt_hostname.setOpaque(false);

        lbl_Address.setForeground(new java.awt.Color(204, 204, 204));
        lbl_Address.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbl_Address.setText("Address:");

        txt_Address.setBackground(new Color(0,0,0,0));
        txt_Address.setForeground(new java.awt.Color(204, 204, 204));
        txt_Address.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txt_Address.setOpaque(false);

        lbl_BAddress.setForeground(new java.awt.Color(204, 0, 0));
        lbl_BAddress.setText("Bad address");

        lbl_BName.setForeground(new java.awt.Color(204, 0, 0));
        lbl_BName.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/help.png"))); // NOI18N
        lbl_BName.setText("Bad name");
        lbl_BName.setToolTipText("Only alphanumeric and spaces. Name can not start with a number.");
        lbl_BName.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        lbl_BName.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        lbl_BName.setIconTextGap(8);

        pn_scan.setOpaque(false);

        javax.swing.GroupLayout pn_scanLayout = new javax.swing.GroupLayout(pn_scan);
        pn_scan.setLayout(pn_scanLayout);
        pn_scanLayout.setHorizontalGroup(
            pn_scanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 616, Short.MAX_VALUE)
        );
        pn_scanLayout.setVerticalGroup(
            pn_scanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 153, Short.MAX_VALUE)
        );

        lbl_Port.setForeground(new java.awt.Color(204, 204, 204));
        lbl_Port.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbl_Port.setText("Port:");

        txt_Port.setBackground(new Color(0,0,0,0));
        txt_Port.setForeground(new java.awt.Color(204, 204, 204));
        txt_Port.setText(String.valueOf(Config.GlobalServerCFG.port));
        txt_Port.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txt_Port.setOpaque(false);

        lbl_BPort.setForeground(new java.awt.Color(204, 0, 0));
        lbl_BPort.setText("Bad port");

        javax.swing.GroupLayout pn_ContainerLayout = new javax.swing.GroupLayout(pn_Container);
        pn_Container.setLayout(pn_ContainerLayout);
        pn_ContainerLayout.setHorizontalGroup(
            pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pn_ContainerLayout.createSequentialGroup()
                .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pn_ContainerLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbl_title))
                    .addGroup(pn_ContainerLayout.createSequentialGroup()
                        .addGap(76, 76, 76)
                        .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lbl_Address, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lbl_hostname)
                            .addComponent(lbl_Port, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(txt_Address)
                                .addComponent(txt_hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txt_Port, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbl_BPort)
                            .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(lbl_BAddress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lbl_BName, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE))))
                    .addGroup(pn_ContainerLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(pn_scan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pn_ContainerLayout.setVerticalGroup(
            pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pn_ContainerLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_title)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_hostname)
                    .addComponent(txt_hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_BName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_Address)
                    .addComponent(txt_Address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_BAddress))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pn_ContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_Port)
                    .addComponent(txt_Port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_BPort))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pn_scan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        bt_accept.setBackground(new java.awt.Color(0, 0, 0));
        bt_accept.setForeground(new java.awt.Color(204, 204, 204));
        bt_accept.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/dialog-ok-apply.png"))); // NOI18N
        bt_accept.setText("Check");
        bt_accept.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        bt_accept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_acceptActionPerformed(evt);
            }
        });

        bt_cancel.setBackground(new java.awt.Color(0, 0, 0));
        bt_cancel.setForeground(new java.awt.Color(204, 204, 204));
        bt_cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/dialog-cancel.png"))); // NOI18N
        bt_cancel.setText("Cancel");
        bt_cancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        bt_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_cancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(423, Short.MAX_VALUE)
                .addComponent(bt_cancel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_accept)
                .addContainerGap())
            .addComponent(pn_Container, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(pn_Container, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_accept)
                    .addComponent(bt_cancel))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bt_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_cancelActionPerformed
        if(autoclose.isRunning())autoclose.stop();
        GUI.loadPlugin(panel);
        GUI.visibleToolBar();
    }//GEN-LAST:event_bt_cancelActionPerformed

    private void bt_acceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_acceptActionPerformed
        if(!autosave){
            if(!Save()){
                bt_accept.setText("Check");
            }
            return;
        }
        hideErrors();
        bt_accept.setText("Checking...");
        bt_accept.setEnabled(false);
        
        if(!IP.isIP(txt_Address.getText().trim()))
            lbl_BAddress.setVisible(true);
        if(!XML.isCorrectName(txt_hostname.getText().trim())){
            lbl_BName.setText("Bad name");
            lbl_BName.setToolTipText("Only alphanumeric and spaces. Name can not start with a number.");
            lbl_BName.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/servermanager/icons/help.png")));
            lbl_BName.setVisible(true);
        }
        try{
            port = Integer.parseInt(txt_Port.getText());
            if(port<1 || port > 65535){
                lbl_BPort.setVisible(true);
            }
        }catch(NumberFormatException ex){
            lbl_BPort.setVisible(true);
        }
        if(panel.childExists(txt_hostname.getText().trim())){
            lbl_BName.setText("Name alredy exists!");
            lbl_BName.setVisible(true);
        }
        if(lbl_BAddress.isVisible()|| lbl_BName.isVisible()|| lbl_BPort.isVisible()){
            bt_accept.setText("Check");
            autosave=true;
            lbl_BName.setToolTipText(null);
            lbl_BName.setIcon(null);
            bt_accept.setEnabled(true);
            return;
        }
        pn_CheckServer checker = new pn_CheckServer(this,txt_Address.getText().trim(),port);
        pn_scan.removeAll();
        checker.setBounds(0, 0, pn_scan.getWidth(), pn_scan.getHeight());
        pn_scan.add(checker);
        pn_scan.setVisible(true);
        Thread thread = new Thread(checker);
        thread.start();
    }//GEN-LAST:event_bt_acceptActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_accept;
    private javax.swing.JButton bt_cancel;
    private javax.swing.JLabel lbl_Address;
    private javax.swing.JLabel lbl_BAddress;
    private javax.swing.JLabel lbl_BName;
    private javax.swing.JLabel lbl_BPort;
    private javax.swing.JLabel lbl_Port;
    private javax.swing.JLabel lbl_hostname;
    private javax.swing.JLabel lbl_title;
    private javax.swing.JPanel pn_Container;
    private javax.swing.JPanel pn_scan;
    private javax.swing.JTextField txt_Address;
    private javax.swing.JTextField txt_Port;
    private javax.swing.JTextField txt_hostname;
    // End of variables declaration//GEN-END:variables

    protected void setManual(){ //If check fail, user must save it manually
        bt_accept.setText("Save (Anyway)");
        autosave=false;
        bt_accept.setEnabled(true);
    }
    protected boolean  Save(){
        panel.addServer(txt_hostname.getText(), txt_Address.getText(), port);
        if(autosave){
            autoclose.start();
        }
        else{
            GUI.loadPlugin(panel);
            GUI.visibleToolBar();
        }
            
        return true;
    }
    private void hideErrors(){
        lbl_BAddress.setVisible(false);
        lbl_BName.setVisible(false);
        lbl_BPort.setVisible(false);
    }
}
